#!/usr/bin/python
import socket,sys,random,time,os

PMS_HOST = 'bob.dev.pmang.com'
PMS_PORT = 8989

MSG_END = '\r\n\0'

REGION_MAX = 17
AGE_MAX = 7
GENDER_MAX = 2

MSG_T={}

class DummyGS:
	def __init__(self,gsID,host,port):
		global MSG_T
		MSG_T['INIT']=('INIT|%s|%d|%s|%d',self.reqInit) # ProcGSID,dwProcessID,IP,Port
		MSG_T['HBREQ']=('HBANS|%s|%s',self.resHBREQ) # ProcGSID,HBseq
		MSG_T['PERE']=('PEAN|%s|%s',self.resPERE) # ProcGSID, count 10
		MSG_T['STRE']=('STAN|%s|%d|%s',self.resSTRE) # ProcGSID,TotalUser,Stats...
		MSG_T['ANNO']=('OK%',self.resANNO)
	
		self.m_gsID = gsID
		self.m_host = host
		self.m_port = port
		self.m_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		
	def __del__(self):
		self.m_sock.close()	

	def run(self):
		self.m_sock.connect((self.m_host,self.m_port))	
		self.reqInit()
		while 1:
			self.dispatchMessage()
	
	def reqInit(self):
		msg = MSG_T['INIT'][0] % (self.m_gsID,os.getpid(),self.m_host,self.m_port)
		self.m_sock.send(msg.replace('|','%')+MSG_END)

	def resHBREQ(self,body):
		return MSG_T['HBREQ'][0] % (self.m_gsID,body[1])

	def resPERE(self,body):
		perfL = []
		for i in range(0,10):
			perfL.append(str(random.randrange(0,100)))
		
		return MSG_T['PERE'][0] % (self.m_gsID,'%'.join(perfL))

	def resSTRE(self,body):
		tempL = []
		totalUserCnt = 0
		for x in range(0,REGION_MAX):
			ageL = []
			for y in range(0,AGE_MAX):
				genderL = []
				for z in range(0,GENDER_MAX):
					userCnt = random.randrange(0,100)
					totalUserCnt += userCnt
					genderL.append(str(userCnt))
				ageL.append(genderL)
			tempL.append(ageL)
			
		statL = []
		for x in range(0,REGION_MAX):
			for y in range(0,AGE_MAX):
				for z in range(0,GENDER_MAX):
					statL.append(tempL[x][y][z])
					
		return MSG_T['STRE'][0] % (self.m_gsID,totalUserCnt,'%'.join(statL))
		
	def resANNO(self,body):
		print '[dummyGS]PMS noti: %s - %s' % (body[2],body[1])		
		
	def dispatchMessage(self):
		resMsg = self.m_sock.recv(1024)
		body = resMsg.rstrip(MSG_END).split('%')
		if body[0] in MSG_T.keys():
			msg = MSG_T[body[0]][1](body)
			if None != msg:
				self.m_sock.send(msg.replace('|','%')+MSG_END)

	

if __name__ == '__main__':
	if(len(sys.argv) < 4 ):
		print 'GS start fail!! insufficient parameter'
		
	gsID = sys.argv[2].lstrip('/GSID:')
	haIP = sys.argv[3].lstrip('/HAIP:')
	haPort = int(sys.argv[4].lstrip('/HAPORT:'))
	
	gs = DummyGS(gsID,haIP,haPort)
	gs.run()
	
